<?php
/**
 * @copyright: ©2024 永州 微聚商网络科技有限公司
 * @link: https://www.wEijuyunke.com
 */
namespace app\mobile\controller;

use app\admin\model\FigureBalanceLog;
use app\admin\model\FigureBrokerage;
use app\admin\model\template\CheckFail;
use app\admin\model\template\GenerateSuccess;
use app\admin\model\template\Task;
use app\BaseController;
use think\App;
use think\facade\Request;
use think\facade\Db;
use think\facade\Log;
use think\Model;
use app\admin\model\FigureUser;
use app\admin\model\FigureVideo;
use app\admin\model\FigureCompositeAvatar;
use app\admin\model\FigureSynthesisAvatar;
use app\admin\model\FigureCompositeSound;
use app\admin\model\FigureAvatar;
use app\admin\model\FigureVoiceTwin;

/**
 * 回调操作
 *
 * @author Administrator
 *
 */
class Callback extends BaseController
{

    /**
     * 高级回调
     * http://aigc.weijuyunke.cn/mobile/timer/synthesisCallback
     */
    public function synthesisCallback()
    {
        try {
            Log::write("Callback synthesisCallback " . json_encode(array(
                    'taskType' => input('taskType'),
                    'data' => input('data')
                )), 'info');

            if (input('taskType')) {

                $taskType = input('taskType');
                $data = input('data');

                switch ($taskType) {
                    case 'video-training':
                        $data['decode_img'] = isset($data['url_image']) ? $data['url_image'] : '';
                        if (isset($data['current_status'])){
                            $updateData['current_status'] = $data['current_status'];
                        }
                        if (isset($data['new_current_status'])){
                            $updateData['new_current_status'] = $data['new_current_status'];
                        }
                        if (isset($data['composite_current_status'])){
                            $updateData['composite_current_status'] = $data['composite_current_status'];
                        }
                        if (isset($data['four_current_status'])){
                            $updateData['four_current_status'] = $data['four_current_status'];
                        }

                        FigureAvatar::where([
                            '_id' => $data['id']
                        ])->save($updateData);
                        break;
                    case 'video-synthesis':
                        $FigureVideoInfo = FigureVideo::where("_id", $data['id'])->find();
                        FigureVideo::where([
                            '_id' => $data['id']
                        ])->save([
                            'current_status' => isset($data['current_status']) ? $data['current_status'] : '',
                            'result' => isset($data['result']) ? $data['result'] : '',
                            'result_cover' => isset($data['result_cover']) ? $data['result_cover'] : '',
                           
                        ]);

                        if ($data['current_status'] == 'success') {
                            if ($FigureVideoInfo['is_batch_generate'] == 1 && $FigureVideoInfo['current_status'] == 'init') {
                                $batchGenerateList = FigureVideo::where("log_no", $FigureVideoInfo['log_no'])->select();
                                $isSend = 1;
                                $successCount = 0;
                                $failCount = 0;
                                foreach ($batchGenerateList as $value) {
                                    if ($value['current_status'] == 'wait_sent' || $value['current_status'] == 'init') {
                                        $isSend = 0;
                                        if ($value['current_status'] == 'success') {
                                            $successCount++;
                                        }
                                        if ($value['current_status'] == 'fail') {
                                            $failCount++;
                                        }

                                    }
                                }
                                if ($isSend == 1) {
                                    $userModel = new FigureUser();
                                    $userInfo = $userModel->where(['id' => $FigureVideoInfo['uid']])->find();
                                    $generateData ['openid'] = $userInfo['openid'];
                                    $generateData['thing14'] = $FigureVideoInfo['name'];
                                    $generateData['thing4'] = '合成成功' . $successCount . ',失败' . $failCount;
                                    $generateData['date3'] = date('Y-m-d H:i', time());
                                    $generateSuccess = new Task($generateData);
                                    $generateSuccess->send();
                                }
                            } else {
                                if ($FigureVideoInfo['current_status'] == 'init') {
                                    $userModel = new FigureUser();
                                    $userInfo = $userModel->where(['id' => $FigureVideoInfo['uid']])->find();
                                    $generateData ['openid'] = $userInfo['openid'];
                                    $generateData['thing1'] = $FigureVideoInfo['name'];
                                    $generateData['time2'] = date('Y-m-d H:i', time());
                                    $generateData['thing3'] = '视频合成生成';
                                    $generateSuccess = new GenerateSuccess($generateData);
                                    $generateSuccess->send();
                                }

                            }

                        }

                        if ($data['current_status'] == 'fail') {
                            if ($FigureVideoInfo['is_batch_generate'] == 1 && $FigureVideoInfo['current_status'] == 'init') {
                                $batchGenerateList = FigureVideo::where("log_no", $FigureVideoInfo['log_no'])->select();
                                $isSend = 1;
                                $successCount = 0;
                                $failCount = 0;
                                foreach ($batchGenerateList as $value) {
                                    if ($value['current_status'] == 'wait_sent' || $value['current_status'] == 'init') {
                                        $isSend = 0;
                                        if ($value['current_status'] == 'success') {
                                            $successCount++;
                                        }
                                        if ($value['current_status'] == 'fail') {
                                            $failCount++;
                                        }

                                    }
                                }
                                if ($isSend == 1) {
                                    $userModel = new FigureUser();
                                    $userInfo = $userModel->where(['id' => $FigureVideoInfo['uid']])->find();
                                    $generateData ['openid'] = $userInfo['openid'];
                                    $generateData['thing14'] = $FigureVideoInfo['name'];
                                    $generateData['thing4'] = '合成成功' . $successCount . ',失败' . $failCount;
                                    $generateData['date3'] = date('Y-m-d H:i', time());
                                    $generateSuccess = new Task($generateData);
                                    $generateSuccess->send();
                                }
                            } else {
                                if ($FigureVideoInfo['current_status'] == 'init') {
                                    $userModel = new FigureUser();
                                    $userInfo = $userModel->where(['id' => $FigureVideoInfo['uid']])->find();
                                    $generateData ['openid'] = $userInfo['openid'];
                                    $generateData['thing1'] = $FigureVideoInfo['name'];
                                    $generateData['time2'] = date('Y-m-d H:i', time());
                                    $generateData['thing3'] = '视频合成生成';
                                    $generateSuccess = new GenerateFail($generateData);
                                    $generateSuccess->send();
                                }

                            }

                        }
                        break;

                    default:
                        break;
                }
            }
        } catch (\Exception $e) {
            Log::error("Callback  synthesisCallback:异常" . $e->getMessage() . "+++" . $e->getLine());
            return result(- 1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 标准回调
     * http://aigc.weijuyunke.cn/mobile/timer/compositeCallback
     */
    public function compositeCallback()
    {
        try {

            Log::write("Callback compositeCallback " . json_encode(array(
                    'taskType' => input('taskType'),
                    'data' => input('data')
                )), 'info');

            if (input('taskType')) {

                $taskType = input('taskType');

                $data = input('data');


                switch ($taskType) {

                    case 'voice-training':
                        $update= [];
                        $update['current_status']= isset($data['current_status']) ? $data['current_status']:'';
                        if (isset($data['is_status'])){
                            $row =   FigureVoiceTwin::where([
                                '_id' => $data['id']
                            ])->find();
                            $update['is_status']= $data['is_status'];

                            if ($data['is_status'] == 3){
                                $user = FigureUser::where('id', $row['uid'])->find();
                                if ($row['train_mode'] == 1) {
                                    $desc = '声音克隆标准版';
                                    $money = sysconfig('tally', 'voice_deduct');

                                } elseif ($row['train_mode'] == 2) {
                                    $tally = sysconfig('tally', 'voice_high_deduct');
                                    $desc = '声音克隆高保真';
                                } else {
                                    $money = sysconfig('tally', 'xunfei_sound_train');
                                    $desc = '声音克隆专业版';
                                }


                                $insertLog = array(
                                    'uid' => $row['uid'],
                                    'type' => 1,
                                    'way' => 3,
                                    'desc' => $desc
                                );


                                $b_type = 1;
                                $current = $user['balance'];

                                $log_no = getPayNo('VC');
                                if ($row['log_no']) {
                                    $log_no = $row['log_no'];
                                    $balanceLog = FigureBalanceLog::where('log_no', $row['log_no'])->find();
                                    if ($balanceLog) {
                                        $money = $balanceLog['money'];
                                        $tally = $balanceLog['tally'];
                                        $b_type = $balanceLog['b_type'];
                                        if ($b_type == 1) {
                                            $desc = '声音克隆标准版';
                                            $current = $user['balance'];

                                        } elseif ($row['train_mode'] == 2 && $b_type == 2) {
                                            $current = $user['voice_twin_count'];
                                        } elseif ($row['train_mode'] == 3 && $b_type == 2) {
                                            $current = $user['xunfei_sound_clone_words_number'];
                                        }
                                        //$current = $b_type == 1 ? $user['balance'] : $user['voice_twin_count'];
                                    }
                                }

                                $insertLog['b_type'] = $b_type;
                                $insertLog['log_no'] = $log_no;
                                $insertLog['current'] = $current;
                                $insertLog['tally'] = $tally;
                                $insertLog['money'] = $money;

                                $log = new \app\admin\model\FigureBalanceLog();
                                $log->save($insertLog);

                                if ($b_type == 1) {
                                    FigureUser::where('id', $row['uid'])->save([
                                        'balance' => Db::raw('balance+' . $money)
                                    ]);
                                } elseif ($b_type == 2 && $row['train_mode'] == 2) {
                                    FigureUser::where('id', $row['uid'])->save([
                                        'voice_twin_count' => Db::raw('voice_twin_count+' . 1)
                                    ]);
                                } elseif ($b_type == 2 && $row['train_mode'] == 3) {
                                    FigureUser::where('id', $row['uid'])->save([
                                        'xunfei_sound_clone_words_number' => Db::raw('xunfei_sound_clone_words_number+' . 1)
                                    ]);
                                }
                                $checkfail = new CheckFail([
                                    'openid' => $user['openid'],
                                    'type' => $desc,
                                    'name' => $row['name'],
                                    'result' => '驳回',
                                    'refuse' => isset($data['refuse']) ? $data['refuse'] : '已驳回'
                                ]);
                                $checkfail->send();
                            }

                        }
                        FigureVoiceTwin::where([
                            '_id' => $data['id']
                        ])->save(
                            $update
                            /*[
                            'current_status' => isset($data['current_status']) ? $data['current_status'] : ''
                        ]*/);
                        break;

                    case 'voice-synthesis':

                        FigureCompositeSound::where([
                            '_id' => $data['id']
                        ])->save([
                            'url' => isset($data['url']) ? $data['url'] : ''
                        ]);
                        break;

                    case 'video-training':

                        FigureAvatar::where([
                            '_id' => $data['id']
                        ])->save([
                            'composite_current_status' => isset($data['current_status']) ? $data['current_status'] : ''
                        ]);
                        break;

                    case 'video-synthesis':
                        $FigureVideoInfo = FigureVideo::where("_id", $data['id'])->find();
                        FigureVideo::where([
                            '_id' => $data['id']
                        ])->save([
                            'current_status' => isset($data['current_status']) ? $data['current_status'] : '',
                            'result' => isset($data['result']) ? $data['result'] : '',
                            'result_cover' => isset($data['result_cover']) ? $data['result_cover'] : '',

                        ]);

                        if ($data['current_status'] == 'success') {
                            if ($FigureVideoInfo['is_batch_generate'] == 1 && $FigureVideoInfo['current_status'] == 'init') {
                                $batchGenerateList = FigureVideo::where("log_no", $FigureVideoInfo['log_no'])->select();
                                $isSend = 1;
                                $successCount = 0;
                                $failCount = 0;
                                foreach ($batchGenerateList as $value) {
                                    if ($value['current_status'] == 'wait_sent' || $value['current_status'] == 'init') {
                                        $isSend = 0;
                                        if ($value['current_status'] == 'success') {
                                            $successCount++;
                                        }
                                        if ($value['current_status'] == 'fail') {
                                            $failCount++;
                                        }

                                    }
                                }
                                if ($isSend == 1) {
                                    $userModel = new FigureUser();
                                    $userInfo = $userModel->where(['id' => $FigureVideoInfo['uid']])->find();
                                    $generateData ['openid'] = $userInfo['openid'];
                                    $generateData['thing14'] = $FigureVideoInfo['name'];
                                    $generateData['thing4'] = '合成成功' . $successCount . ',失败' . $failCount;
                                    $generateData['date3'] = date('Y-m-d H:i', time());
                                    $generateSuccess = new Task($generateData);
                                    $generateSuccess->send();
                                }
                            } else {

                                if ($FigureVideoInfo['current_status'] == 'init') {
                                    $userModel = new FigureUser();
                                    $userInfo = $userModel->where(['id' => $FigureVideoInfo['uid']])->find();
                                    $generateData ['openid'] = $userInfo['openid'];
                                    $generateData['thing1'] = $FigureVideoInfo['name'];
                                    $generateData['time2'] = date('Y-m-d H:i', time());
                                    $generateData['thing3'] = '视频合成生成';
                                    $generateSuccess = new GenerateSuccess($generateData);
                                    $generateSuccess->send();
                                }
                            }

                        }
                        if ($data['current_status'] == 'fail') {
                            if ($FigureVideoInfo['is_batch_generate'] == 1 && $FigureVideoInfo['current_status'] == 'init') {
                                $batchGenerateList = FigureVideo::where("log_no", $FigureVideoInfo['log_no'])->select();
                                $isSend = 1;
                                $successCount = 0;
                                $failCount = 0;
                                foreach ($batchGenerateList as $value) {
                                    if ($value['current_status'] == 'wait_sent' || $value['current_status'] == 'init') {
                                        $isSend = 0;
                                        if ($value['current_status'] == 'success') {
                                            $successCount++;
                                        }
                                        if ($value['current_status'] == 'fail') {
                                            $failCount++;
                                        }

                                    }
                                }
                                if ($isSend == 1) {
                                    $userModel = new FigureUser();
                                    $userInfo = $userModel->where(['id' => $FigureVideoInfo['uid']])->find();
                                    $generateData ['openid'] = $userInfo['openid'];
                                    $generateData['thing14'] = $FigureVideoInfo['name'];
                                    $generateData['thing4'] = '合成成功' . $successCount . ',失败' . $failCount;
                                    $generateData['date3'] = date('Y-m-d H:i', time());
                                    $generateSuccess = new Task($generateData);
                                    $generateSuccess->send();
                                }
                            } else {
                                if ($FigureVideoInfo['current_status'] == 'init') {
                                    $userModel = new FigureUser();
                                    $userInfo = $userModel->where(['id' => $FigureVideoInfo['uid']])->find();
                                    $generateData ['openid'] = $userInfo['openid'];
                                    $generateData['thing1'] = $FigureVideoInfo['name'];
                                    $generateData['time2'] = date('Y-m-d H:i', time());
                                    $generateData['thing3'] = '视频合成生成';
                                    $generateSuccess = new GenerateFail($generateData);
                                    $generateSuccess->send();
                                }

                            }

                        }

                        break;

                    default:
                        break;
                }
            }
        } catch (\Exception $e) {
            Log::error("Callback  compositeCallback:异常" . $e->getMessage() . "+++" . $e->getLine());
            return result(- 1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    public function wxCallback(){
        $getCallBackJson = file_get_contents('php://input');
        file_put_contents('./log/' . date('Y-m-d') . 'rechargedata.txt', $getCallBackJson . PHP_EOL, FILE_APPEND);
        $getCallBackArray = json_decode($getCallBackJson, true);
        $associatedData = $getCallBackArray['resource']['associated_data'];
        $nonceStr = $getCallBackArray['resource']['nonce'];
        $ciphertext = $getCallBackArray['resource']['ciphertext'];
        $ciphertext = \base64_decode($ciphertext);
        $ctext = substr($ciphertext, 0, -16);
        $authTag = substr($ciphertext, -16);
        $payConfig = sysconfig('pay');
        $apiKey = $payConfig['pay_api_key'];
        $str = \openssl_decrypt($ctext, 'aes-256-gcm', $apiKey, \OPENSSL_RAW_DATA, $nonceStr, $authTag, $associatedData);
        $result = json_decode($str, true);
        if ($result['trade_state'] == 'SUCCESS') {
            $FigureBrokerageModel = new FigureBrokerage();
            $out_trade_no = $result['out_bill_no'];
            $rechargeOrderInfo =  $FigureBrokerageModel->where(['order_sn' =>$out_trade_no] )->find();
            if ($rechargeOrderInfo['status'] == 1){
                if ($result['state'] == 'SUCCESS' ){
                     $FigureBrokerageModel->where(['order_sn' =>$out_trade_no] )->update(['status' => 2]);
                }
                if ($result['state'] == 'FAIL' ){
                    $FigureBrokerageModel->where(['order_sn' =>$out_trade_no] )->update(['status' => 3]);
                }
            }

        }
    }
}